#include "logindlg.h"
#include "ui_logindlg.h"

QSet<TargetUser> targetUserSet;
QSet<Procedure> t_procedure_set;
ProjectInfo targetProject;

loginDlg::loginDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::loginDlg)
{
//    initialize window
    ui->setupUi(this);

    setWindowTitle("登陆");

    ui->status_label->setText("启动数据库连接");
    ui->lock_btn->setCheckable(true);

    ui->lock_btn->setIcon(QIcon(":/res/res/locked.svg"));

    ui->login_btn->setEnabled(false);

    connect(this, SIGNAL(signal_DbConnected()), this, SLOT(slot_DbConnected()));
    connect(this, SIGNAL(signal_ProjectListConstructed()), this, SLOT(slot_ProjectListConstructed()));
    connect(this, SIGNAL(signal_ParameterLocked()), this, SLOT(slot_ParameterLocked()));
    connect(this, SIGNAL(signal_ParameterUnlocked()), this, SLOT(slot_ParameterUnlocked()));

    //make connection
    f_MakeConnToDb();
//    ui->passwordInput->setEchoMode(QLineEdit::Password);
    Logger logger;
}

loginDlg::~loginDlg()
{
    delete ui;      
    qDebug() << "login deleted";
}

bool loginDlg::f_MakeConnToDb()
{
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setUserName("root");
    db.setPassword("");
    db.setDatabaseName("test");
    db.open();

    if(!db.open()){
        QMessageBox::critical(nullptr,
                              "错误",
                              "无法连接到数据库",
                              QMessageBox::Ok | QMessageBox::Cancel);
        logger.writeLog(Logger::DbConnectionFaild);
        return false;
    }
    else {
        ui->status_label->setText("已连接数据库，即将查询可用部件");
        emit(signal_DbConnected());
    }
    return true;
}

//bool loginDlg::loginVerify(QString usrId, QString pwd)
//{
//    md5(pwd);

//    QSqlQuery query(db);
//    query.exec("select a.usr_pwd, "
//               "a.usr_name, "
//               "a.usr_set_ip, "
//               "usr_set_port from t_usr a where a.usr_id = "
//               + usrId);
//    query.next();
//    qDebug() << query.value("usr_set_ip").toString();

//    if(md5(pwd) == query.value("usr_pwd").toString()){
//        loginId = usrId;
//        loginName = query.value("usr_name").toString();
//        host = query.value("usr_set_ip").toString();
//        port = (unsigned short) query.value("usr_set_port").toUInt();
//        return true;
//    }

//    else {
//        return false;
//    }
//}

void loginDlg::on_exit_btn_clicked()
{
    qApp->exit();
}

void loginDlg::slot_DbConnected()
{
    QSqlQuery query(db);
    query.exec("select project_name, "
               "project_url, "
               "project_person_num, "
               "project_level, "
               "project_career,"
               "project_num"
               " from t_project");
    while(query.next())
    {
        ProjectInfo temp(query.value(0).toString(),
                         query.value(1).toString(),
                         query.value(2).toInt(),
                         query.value(3).toString(),
                         query.value(4).toString(),
                         query.value(5).toInt());
        projInfoList.append(temp);
    }
    ui->status_label->setText("查询执行完成");
    emit(signal_ProjectListConstructed());
}

void loginDlg::slot_ProjectListConstructed() const
{
    int i = 0;
    while(i < projInfoList.length())
    {
        ui->projSelectComboBox->addItem(projInfoList.at(i).getName());
        ++i;
    }
}

void loginDlg::on_login_btn_clicked()
{
    if(queryThread != nullptr)
    {
        queryThread->stopThread();
    }

//    if(f_MakeConnToDb()){
//        if(loginVerify(ui->usrnameInput->text(), ui->passwordInput->text())){
    fileSelectDlg *fileSelect = new fileSelectDlg();

    QSqlQuery query(db);
    query.exec(QString("SELECT "
               "a.procedure_idx,"
               "a.procedure_name "
               "FROM "
               "t_procedure a "
               "WHERE "
               "a.procedure_project_name = '%1'").arg(targetProject.getName()));

    while(query.next())
    {
        Procedure t_procedure(query.value(0).toString(), query.value(1).toString(), 2);
        t_procedure_set.insert(t_procedure);

        qDebug() << query.value(0).toString() << "\t" << query.value(1).toString() << endl;
    }

    fileSelect;

    if(targetProject.isEmpty())
    {
        host = targetProject.getUrl().mid(6, targetProject.getUrl().indexOf('\\', 6) - 6);
        port = 21;
    }
//            fileSelect->setUserNum(loginId);
////            fileSelect->setUsername(loginName);

//            logger.setUsrname(loginName);
    if(!host.isNull() && port != 0)
    {
        fileSelect->setHostAndPort(host, port);
//                logger.setIpAndPort(host, port);
    }
//            else {
//                logger.setIpAndPort(QHostAddress("10.16.25.58"), 3306);
//            }
//            logger.writeLog(Logger::LoginSuccessfully);

     fileSelect->setAttribute(Qt::WA_DeleteOnClose);
     fileSelect->show();
     fileSelect->connectToServer();
//            fileSelect->check();
     this->close();
//        }
//        else {
//            QMessageBox::critical(nullptr,
//                                  "错误",
//                                  "登陆失败，请检查用户名或密码",
//                                  QMessageBox::Ok);
//            logger.writeLog(Logger::WrongUserNameOrPassword);
//            return;
//        }
//    }
//    else
//        this->close();
}

//QString loginDlg::md5(QString str)
//{
//    QString strPwdMd5 = QCryptographicHash::hash(str.toUtf8(),
//                                                 QCryptographicHash::Md5).toHex();
//    return strPwdMd5;
//}

void loginDlg::on_projSelectComboBox_currentIndexChanged(int index)
{
    ui->person_level_label->clear();
    ui->person_work_label->clear();
    ui->person_num_label->clear();
    ui->part_num_label->clear();

    ui->person_level_label->setText(projInfoList.at(index).getLevel());
    ui->person_work_label->setText(projInfoList.at(index).getCareer());
    ui->person_num_label->setText(QString::number(projInfoList.at(index).getPersonNum()));
    ui->part_num_label->setText(QString::number(projInfoList.at(index).getNum()));
}

void loginDlg::on_lock_btn_toggled(bool checked)
{
    if(checked)
    {
        QList <QComboBox *> comboList = findChildren<QComboBox *>();
        QListIterator<QComboBox*>combo_iterator(comboList);

        while(combo_iterator.hasNext())
        {
            combo_iterator.next()->setEnabled(false);
        }
        ui->lock_btn->setIcon(QIcon(":/res/res/unlocked.svg"));
        emit(signal_ParameterLocked());
        ui->status_label->setText("参数锁定，等待用户接入");
    }
    else
    {
        ui->login_btn->setEnabled(false);

        QList <QComboBox *> comboList = findChildren<QComboBox *>();
        QListIterator<QComboBox*>combo_iterator(comboList);

        while(combo_iterator.hasNext())
        {
            combo_iterator.next()->setEnabled(true);
        }
        ui->lock_btn->setIcon(QIcon(":/res/res/locked.svg"));
        if(queryThread != nullptr)
        {
            queryThread->stopThread();
        }
        emit(signal_ParameterUnlocked());
        ui->status_label->setText("参数解锁，请锁定参数后重新接入");
    }
}

void loginDlg::slot_ParameterLocked()
{
//    ProjectInfo *targetProject = new ProjectInfo(ui->projSelectComboBox->currentText(),
//                                                projInfoList.at(ui->projSelectComboBox->currentIndex()).getUrl(),
//                                                ui->personNumSelectComboBox->currentText().toInt(),
//                                                ui->levelSelectComboBox->currentText(),
//                                                ui->careerSelectComboBox->currentText());

    for(int i = 0; i < projInfoList.count(); ++i)
    {
        if(projInfoList.at(i).getName() == ui->projSelectComboBox->currentText())
        {
            targetProject = projInfoList.at(i);
        }
    }

    queryThread = new StepQueryThread();
    queryThread->setRowCnt(3);

    connect(queryThread, SIGNAL(emitInfo(QStringList)), this, SLOT(processQuerySignal(QStringList)));

    queryThread->setQuery(QString("SELECT a.usr_id, a.usr_name, a.usr_level "
                                  "FROM t_usr a "
                                  "INNER JOIN t_login b ON b.usr_id = a.usr_id "
                                  "WHERE b.login_machine = 'localhost' "
                                  "AND b.operation_time BETWEEN '%1' AND '%2 23:59:59' "
                                  "AND a.usr_career = '%3' "
                                  "ORDER BY b.operation_time DESC "
                                  "LIMIT 1 ").arg(queryThread->getTime())
                                             .arg(queryThread->getTime()
                                                  .split(" ")[0])
                                             .arg(ui->person_work_label->text()));
    queryThread->start();
}

void loginDlg::slot_ParameterUnlocked()
{
    targetUserSet.clear();
    qDebug() << "集合已经清空";

    lastSetCnt = 0;
    targetLoginNumber = 0;
}

void loginDlg::processQuerySignal(QStringList queryList)
{
//    qDebug() << s;
    if(queryList.at(0) != "" || queryList.at(1) != "")
    {
        TargetUser usr_tmp;
        usr_tmp.m_number = queryList.at(0);
        usr_tmp.m_infoSet.append(queryList.at(1));
        usr_tmp.m_infoSet.append(queryList.at(2));

        targetUserSet.insert(usr_tmp);
        judgeLogin(targetUserSet, targetUserSet.count());
        qDebug() << targetUserSet;
    }
}

void loginDlg::judgeLogin(const QSet<TargetUser> &user, int count)
{
    if(count - lastSetCnt != 0)
    {
        targetLoginNumber = 0;

        QSetIterator<TargetUser> iterator(user);
        iterator.toFront();
        while(iterator.hasNext())
        {
            if(iterator.next().m_infoSet[1] == ui->person_level_label->text())
            {
                targetLoginNumber ++;
            }
            else
            {
                ui->status_label->setText(QString("<font color = 'red'>检测到有不符合标准等级的用户试图登录</font>"));
                ui->login_btn->setEnabled(false);

                if(queryThread != nullptr)
                {
                    queryThread->stopThread();
                }
                return;
            }
        }
        //if(iterator.hasNext())
        //{
            //if(iterator.next().m_level == ui->levelSelectComboBox->currentText())
        //}
        if(targetLoginNumber == ui->person_num_label->text().toInt())
        {
            ui->status_label->setText(QString("<font color = \'green\'>与设定情况一致，允许登录</font>"));
            ui->login_btn->setEnabled(true);
        }
        else
        {
            ui->status_label->setText(QString("<font color = \'red\'>需求为%1级%2共%3名，%4%5名</font>")
                                     .arg(ui->person_level_label->text())
                                     .arg(ui->person_work_label->text())
                                     .arg(ui->person_num_label->text())
                                     .arg((ui->person_num_label->text()
                                           .toInt() - targetLoginNumber) > 0 ? "还剩" : "多余")
                                     .arg(qAbs(ui->person_num_label->text()
                                               .toInt() - targetLoginNumber)));
            ui->login_btn->setEnabled(false);
        }
        lastSetCnt = count;
    }
}
